<template>
  <div class="data-table">
    <el-table
      v-loading="loading"
      element-loading-text="拼命加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.6)"
      :data="roles"
      @cell-dblclick="cellDblclick"
      @expand-change="onExpandChange"
    >
      <el-table-column type="expand">
        <template slot-scope="{ row }">
          <div class="users-list-box">
            <div v-if="users[row.id] == undefined || users[row.id].length == 0">无</div>
            <template v-else>
              <el-tag
                v-for="item in users[row.id]"
                :key="item.id"
                size="medium"
                type="primary"
                closable
                @close="handleUserClose(row, item.id)"
              >
                {{ item.realname }}
              </el-tag>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="cname"></el-table-column>
      <el-table-column label="标识" prop="ename"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button type="success" size="mini" @click="dispatchRoleToNodes(row)">
            分配权限
          </el-button>
          <el-button type="primary" size="mini">修改角色</el-button>
          <el-button type="danger" size="mini">删除角色</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background :total="100" layout="prev, pager, next" />
    <el-drawer
      :title="`【${cname}】角角分配权限节点`"
      :visible.sync="drawerVisible"
      direction="ltr"
      :wrapperClosable="false"
      :close-on-press-escape="false"
      :before-close="handleCloseDrawer"
    >
      <!-- 使用key来完成点击不同角色它有不同的key从而实现重新加载 -->
      <el-tree
        :key="roleid"
        :data="nodes"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :props="{ label: 'name' }"
        :default-checked-keys="defaultCheckedKeys"
        @check="nodeCheck"
      >
      </el-tree>
      <br />
      <el-divider></el-divider>
      <br />
      <el-button size="medium" type="primary" @click="saveRoleToNodes"
        >保存当前角色权限节点</el-button
      >
    </el-drawer>
  </div>
</template>

<script>
import { roleidToUsersApi, addRoleToNodesApi } from '@/api/roleApi'
import { editUserInfoApi } from '@/api/userApi'
import { nodesListApi } from '@/api/nodeApi'
export default {
  props: ['page', 'loadData', 'total', 'roles'],
  data() {
    return {
      users: {},
      loading: false,
      drawerVisible: false,
      cname: '',
      nodes: [],
      roleid: 0,
      // 勾选中的
      checkedKeys: [],
      // 父级半选
      halfCheckedKeys: [],
      // 默认选中的节点
      defaultCheckedKeys: []
    }
  },
  mounted() {
    this.loadNodes()
  },
  methods: {
    // 选中权限节点
    nodeCheck(row, { checkedKeys, halfCheckedKeys }) {
      this.checkedKeys = checkedKeys
      this.halfCheckedKeys = halfCheckedKeys
    },
    // 保存角色对应权限节点
    async saveRoleToNodes() {
      let ret = await addRoleToNodesApi(this.roleid, {
        nodes: [...this.checkedKeys, ...this.halfCheckedKeys],
        half_nodes: this.halfCheckedKeys
      })
      console.log(ret)
    },
    // 加载所有的权限节点
    async loadNodes() {
      let ret = await nodesListApi()
      this.nodes = ret.data
    },
    // 加载对象角所下面的用户列表
    loadUser() {
      console.log(arguments)
    },
    // 移除当前角色下面的所属用户
    async handleUserClose(row, userid) {
      // console.log(roleid, userid)
      try {
        await this.$confirm('您确定要把此用户移除掉吗？', '移除确认', {
          confirmButtonText: '确认移除',
          cancelButtonText: '考虑一下'
        })
        // 点击确认，把用户此角色移除
        const ret = await editUserInfoApi(userid, { role: 0 })
        console.log(ret)
        if (ret.code == 0) {
          // 成功
          // console.log('成功')
          this.onExpandChange(row, [1])
        }
      } catch (error) {}
    },
    // 给当前角色分配权限界面展开
    dispatchRoleToNodes({ id: roleid, cname, nodes, half_nodes }) {
      this.drawerVisible = true
      this.cname = cname
      this.roleid = roleid

      // 获取当前它里面所有已分配权限
      nodes = nodes.split(',')
      half_nodes = half_nodes.split(',')
      half_nodes.forEach(item => {
        let index = nodes.indexOf(item)
        if (index >= 0) {
          nodes.splice(index, 1)
        }
      })
      this.defaultCheckedKeys = nodes.map(item => item * 1)
    },
    // 关闭展开的界面
    handleCloseDrawer(done) {
      // 关闭一定要把共用数据给初始化
      this.defaultCheckedKeys = []
      this.checkedKeys = []
      this.halfCheckedKeys = []
      done()
    },
    async onExpandChange(row, expandedRows) {
      const roleid = row.id
      // 只有展开时才进行网络请求，根据当前角色id来获取它所对应的用户列表
      if (expandedRows.length > 0) {
        this.loading = true
        try {
          let ret = await roleidToUsersApi(roleid)
          if (ret.code === 0) {
            // this.users[roleid] = ret.data
            // 动态给对象添加属性
            this.$set(this.users, roleid, ret.data)
          }
        } catch (error) {
        } finally {
          this.loading = false
        }
      }
    },
    cellDblclick(row, column, cell, event) {
      cell.children[0].setAttribute('contenteditable', true)
      cell.children[0].addEventListener('blur', e => {
        cell.children[0].setAttribute('contenteditable', false)
        console.log(e.target.textContent, row.id)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.data-table {
  background: #fff;
  margin-top: 10px;
  padding-bottom: 10px;
}
.users-list-box {
  padding: 10px;
}
.el-tag {
  margin-right: 10px;
}

/* :deep(.cell) {
  outline: none;
  user-select: text;
} */
</style>
